import { Configuration } from "webpack";
import * as fs from "fs";
import * as path from "path";
import { ROOT_DIR } from "./webpack.const";

// 根据环境变量加载环境配置文件
export default function injectEnvVariables(
  config: Configuration,
  isProd: boolean
) {
  const DEV_CONFIG_FILE = path.resolve(ROOT_DIR, ".env.development");
  const PROD_CONFIG_FILE = path.resolve(ROOT_DIR, ".env.production");

  const configFile = isProd
    ? fs.existsSync(PROD_CONFIG_FILE)
      ? PROD_CONFIG_FILE
      : null
    : fs.existsSync(DEV_CONFIG_FILE)
      ? DEV_CONFIG_FILE
      : null;

  config.plugins ??= [];
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  const Dotenv = require("dotenv-webpack");

  if (configFile != null) {
    config.plugins.unshift(
      new Dotenv({
        defaults: configFile,
      })
    );
  } else {
    config.plugins.unshift(new Dotenv());
  }
}
